package com.burst.reptile.framework.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.burst.reptile.common.enums.DelStatus;
import com.burst.reptile.common.enums.UserStatus;
import com.burst.reptile.common.exception.BaseException;
import com.burst.reptile.common.utils.ServletUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.common.utils.ip.AddressUtils;
import com.burst.reptile.common.utils.ip.IpUtils;
import com.burst.reptile.framework.security.LoginUser;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.service.ISysUserService;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户验证处理
 * @author wujin
 * @date: 2020年5月21日 下午6:02:53
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
	
	private final ISysUserService userService;

	private final SysPermissionService permissionService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user = userService.selectUserByUserName(username);
		if (ToolUtil.isEmpty(user)) {
			log.info("登录用户：{} 不存在.", username);
			throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
		} else if (DelStatus.DELETED.getCode().equals(user.getDelFlag())) {
			log.info("登录用户：{} 已被删除.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已被删除");
		} else if (UserStatus.DISABLE.getCode().equals(user.getUserStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			throw new BaseException("对不起，您的账号：" + username + " 已停用");
		}
		return createLoginUser(user);
	}

	public UserDetails createLoginUser(SysUser user) {
		LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
		UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
		String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
		if(ToolUtil.isNotEmpty(userAgent)) {
			// 获取客户端操作系统
			String os = userAgent.getOs().getName();
			// 获取客户端浏览器
			String browser = userAgent.getBrowser().getName();
			loginUser.setBrowser(browser);
			loginUser.setOs(os);
		}
		loginUser.setIpaddr(ip);
		String address = AddressUtils.getRealAddressByIP(ip);
		loginUser.setLoginLocation(address);
		loginUser.setLoginTime(System.currentTimeMillis());
		return loginUser;
	}
}
